package net.tomblog.app.swingheil.parser;

import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import net.tomblog.app.swingheil.model.Article;
import net.tomblog.app.swingheil.oauth.SwingHeilOAuth;
import net.tomblog.app.swingheil.util.L;
import net.tomblog.app.swingheil.util.ParsingException;
import oauth.signpost.basic.DefaultOAuthConsumer;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

/**
 * 네이버 게시판 글 목록을 파싱하는 클래스
 * 
 * @author hyunung.park (parkbear01@gmail.com)
 *
 */
public class NaverArticleParser extends ArticleParser {

	private static final String TAG = "NaverArticleParser";
	
	/* Naver Cafe ArticleList 호출 결과 XML
	<?xml version="1.0" encoding="utf-8"?>
	<message type="response" service="naverservice.community.cafe">
		<result xmlns="nhncorp.naverservice.community.cafe.ArticleList">
	    	<itemCount>1</itemCount>
			<articles>
			   	
				<article>
					<articleid>11478</articleid>
					<menuid>3</menuid>
					<subject><![CDATA[[14th_MT] #1 와ㅡ MT간다! ㅅㅅ/]]></subject>
					<nickname><![CDATA[웅이]]></nickname>
					<writedate>2011.09.28 23:23:38</writedate>
					<newArticle><![CDATA[false]]></newArticle>
					<readCount>159</readCount>
					<commentCount>17</commentCount>
		    	</article>
			    
			</articles>
		</result>
	</message>
	 */
	
	/* Naver Cafe ArticleList 호출 결과 XML (Error 상황)
	<result>
		<message><![CDATA[Authentication failed (인증 실패하였습니다.)]]></message>
		<error_code><![CDATA[024]]></error_code>
	</result>
	 */
	
	private static final String RESULT = "result";
//	private static final String ITEM_COUNT = "itemCount";
	private static final String ARTICLES = "articles";
	private static final String ARTICLE = "article";
	private static final String ARTICLE_ID = "articleid";
	private static final String MENU_ID = "menuid";
	private static final String SUBJECT = "subject";
	private static final String NICKNAME = "nickname";
	private static final String WRITE_DATE = "writedate";
	private static final String NEW_ARTICLE = "newArticle";
	private static final String READ_COUNT = "readCount";
	private static final String COMMENT_COUNT = "commentCount";
	private static final String ERROR_CODE = "error_code";
	
	private static final String OPEN_API_BASE_URL = "http://openapi.naver.com";
	// 게시판 목록 조회용 URL
//    private static final String CAFE_MENU_LIST_URL = OPEN_API_BASE_URL + "/cafe/getMenuList.xml";
	// 글 목록 조회용 URL
    private static final String CAFE_ARTICLE_LIST_URL = OPEN_API_BASE_URL + "/cafe/getArticleList.xml";
    /**
     *  글 내용 조회용 URL
     */
	public static final String CAFE_ARTICLE_READ_URL = "http://m.cafe.naver.com/ArticleRead.nhn?boardtype=L";
    
	public NaverArticleParser() {
		mConsumer = new DefaultOAuthConsumer(SwingHeilOAuth.NAVER_CONSUMER_KEY, SwingHeilOAuth.NAVER_CONSUMER_SECRET);
		mConsumer.setTokenWithSecret(SwingHeilOAuth.MY_NAVER_ACCESS_TOKEN, SwingHeilOAuth.MY_NAVER_TOKEN_SECRET);
	}
	
	public List<Article> getArticleList(String cafeId, String boardId, int searchPage, int searchPerPage) throws Exception {
		L.d(TAG, " >>> called getArticleList()");
		
        URL url = null;
        List<Article> articleList = new ArrayList<Article>();
        
		try {
			url = new URL(CAFE_ARTICLE_LIST_URL 
					+ "?search.clubid=" + cafeId 
					+ "&search.menuid=" + boardId 
					+ "&search.page=" + searchPage 
					+ "&search.perPage=" + searchPerPage);
			
			mRequest = (HttpURLConnection) url.openConnection();
            mConsumer.sign(mRequest);
            mRequest.connect();
            
			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
			XmlPullParser parser = parserCreator.newPullParser();
			parser.setInput(mRequest.getInputStream(), null);
			
//			InputStream inputStream = mRequest.getInputStream();
//			StringBuffer sb = new StringBuffer();
//			byte[] b = new byte[4096];
//			for (int n; (n = inputStream.read(b)) != -1;) {
//				sb.append(new String(b, 0, n));
//			}
//			L.e(TAG, "response : " + sb.toString());
			
			int parserEvent = parser.getEventType();
			Article article = null;
			String tag = null;
			DateFormat sdFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
			
			while (parserEvent != XmlPullParser.END_DOCUMENT) {
				if(mIsCanceled) {
					break;
				}
				switch (parserEvent) {
				case XmlPullParser.START_TAG:
					tag = parser.getName();
//					L.d(TAG, "start tag : " + tag);
					if(tag.equals(ARTICLE)) {
						article = new Article();
						article.setCafeId(cafeId);
					}else if(tag.equals(ARTICLES)){
					}
					break;
				case XmlPullParser.TEXT:

					String text = parser.getText().trim();
					if(!text.equals("")) {
//						L.d(TAG, "text : " + parser.getText() + "[" + text.length() + "]");
						if(tag.equals(ARTICLE_ID)) {
							article.setArticleId(Integer.parseInt(text));
						}else if(tag.equals(MENU_ID)) { 
							article.setBoardId(text);
						}else if(tag.equals(SUBJECT)) {
							article.setArticleTitle(text);
						}else if(tag.equals(NICKNAME)) {
							article.setNickname(text);
						}else if(tag.equals(WRITE_DATE)) {
							article.setWriteDate(sdFormat.parse(text));
						}else if(tag.equals(NEW_ARTICLE)) {
							article.setNewArticle(Boolean.parseBoolean(text));
						}else if(tag.equals(READ_COUNT)) {
							article.setReadCount(Integer.parseInt(text));
						}else if(tag.equals(COMMENT_COUNT)) {
							article.setCommentCount(Integer.parseInt(text));
						}else if(tag.equals(ERROR_CODE)) {
							throw new ParsingException(text);
						}
					}
					break;  
				case XmlPullParser.END_TAG:
					tag = parser.getName();
//					L.d(TAG, "end tag : " + tag);
					if(tag.equals(ARTICLE)) {
						articleList.add(article);
					}else if(tag.equals(RESULT)){  
					}
					break;
				}
				parserEvent = parser.next();
			}

		} catch (Exception e) {
			throw e;
		}
		
		return articleList;
	}

	public String getArticleReadURL(Article article) {
		String url = CAFE_ARTICLE_READ_URL 
						+ "&clubid=" + article.getCafeId() 
						+ "&articleid=" + article.getArticleId() 
						+ "&menuid=" + article.getBoardId();
		return url;
	}
}